package middleware

import (
	"go_stu_gin/config"
	"io/ioutil"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func RequestLogger() gin.HandlerFunc {
	logger := config.MyCtx.Log
	return func(c *gin.Context) {
		c.Next()
		//请求方式
		method := c.Request.Method
		//请求路由
		reqUrl := c.Request.RequestURI
		//状态码
		statusCode := c.Writer.Status()
		//请求ip
		clientIP := c.ClientIP()
		// 请求体
		clientBody, _ := ioutil.ReadAll(c.Request.Body)
		clientBodyStr := strings.Replace(string(clientBody), " ", "", -1)
		// 请求的格式
		contentType := c.Request.Header.Values("content-type")
		// 打印日志
		logger.WithFields(logrus.Fields{
			"status_code":  statusCode,
			"client_ip":    clientIP,
			"req_method":   method,
			"req_uri":      reqUrl,
			"body":         clientBodyStr,
			"content_type": contentType,
		}).Info()
	}
}
